//
//  PictureBrowserViewController.swift
//  JLWeibo
//
//  Created by sunjinliang on 15/12/18.
//  Copyright © 2015年 sunjinliang. All rights reserved.
//

import UIKit
import SVProgressHUD
let pictureBrowaerID = "pictureBrowaerID"
class PictureBrowserViewController: UIViewController {
    let thumbnailURLs : [NSURL]
    let indexPath : NSIndexPath
    override func viewDidLoad() {
        super.viewDidLoad()

    }
    init(thumbnailURLs:[NSURL],indexPath:NSIndexPath){
        self.thumbnailURLs = thumbnailURLs
        self.indexPath = indexPath
//        print("----\(thumbnailURLs)---\(indexPath)")
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private lazy var closeButton: UIButton = {
       let btn = UIButton(title: "关闭", image: nil, color: UIColor.whiteColor(), fontSize: 14)
        btn.backgroundColor = UIColor.darkGrayColor()
        btn.addTarget(self, action: "closeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    private lazy var saveButton: UIButton = {
        let btn = UIButton(title: "保存", image: nil, color: UIColor.whiteColor(), fontSize: 14)
        btn.backgroundColor = UIColor.darkGrayColor()
        btn.addTarget(self, action: "saveButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PictureBrowserLayout())
    class PictureBrowserLayout: UICollectionViewFlowLayout {
        override func prepareLayout() {
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            itemSize = (collectionView?.bounds.size)!
            scrollDirection = .Horizontal
            collectionView?.bounces = true
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
    override func loadView() {
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        view = UIView(frame: rect)
        setupUI()
    }
    func saveButtonClick(){
        let cell = collectionView.visibleCells()[0] as! PictureBrowserCell
        guard let image = cell.imgView.image else{
            return
        }
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    func image(image : UIImage , didFinishSavingWithError error : NSError?, contextInfo : AnyObject?){
        let message =  error == nil ? "上帝,您的照片已保存":"sorry,保存失败"
//        SVProgressHUD.showInfoWithStatus(message)
        SVProgressHUD.showImage(UIImage(named: "123"), status: message, maskType: SVProgressHUDMaskType.Gradient)
        
    }
    func closeButtonClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    override func viewWillAppear(animated: Bool) {
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    func setupUI(){
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        collectionView.frame = view.bounds
        closeButton.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left).offset(8)
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.width.equalTo(120)
            make.height.equalTo(30)
        }
        saveButton.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(view.snp_right).offset(-28)
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.width.equalTo(120)
            make.height.equalTo(30)
            prepareCollectionView()
        }
    }
    func prepareCollectionView(){
        
        collectionView.dataSource = self
        collectionView.registerClass(PictureBrowserCell.self, forCellWithReuseIdentifier: pictureBrowaerID)
        
    }
    
}

extension PictureBrowserViewController : PictureBrowserCellClickImageOutDelegate{
    func PictureBrowserCellClickImageOut() {
        closeButtonClick()
    }
    func PictureBrowserCellDidZoom(scale: CGFloat) {
        let isHidden = scale<1
        hiddenView(isHidden)
        
        if isHidden {
            view.transform = CGAffineTransformMakeScale(scale, scale)
        }else{
            view.transform = CGAffineTransformIdentity
        }
    }
    func hiddenView(isHidden:Bool){
        closeButton.hidden = isHidden
        saveButton.hidden = isHidden
        collectionView.backgroundColor = isHidden ? UIColor.clearColor():UIColor.blackColor()
    }
    
}
// MARK: - 过渡动画的代理方法 

extension PictureBrowserViewController :PictureBrowerDismissDeldegate{
    func imageViewFromeDissmiss() -> UIImageView {
        let iv = UIImageView()
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        let cell = collectionView.visibleCells()[0] as? PictureBrowserCell
        iv.frame = (cell?.convertRect((cell?.imgView.frame)!, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!))!
        iv.image = cell?.imgView.image
        
        return iv
    }
    func indexPathFromeDissmiss() -> NSIndexPath {
        return collectionView.indexPathsForVisibleItems()[0]
    }
}
extension PictureBrowserViewController : UICollectionViewDataSource{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return thumbnailURLs.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureBrowaerID, forIndexPath: indexPath) as? PictureBrowserCell
        cell?.imageURL = thumbnailURLs[indexPath.item]
        cell?.CellClickImageDelegate = self
        return cell!
    }
    
    
    
}